package com.sykj.util;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.github.wxpay.sdk.WXPayUtil;

/**
 * http 帮助类
 * @Author vains
 * @Date 2019/6/30 13:36
 **/
public class HttpClientUtils {
	
	public static final String APPID = "wx5a1f8c8c75d0f886";
	public static final String APPSECRET = "4434ba5617c6bd2a13a3652b65156c6d";

	/**
	 * 执行get请求，
	 * @param url 要请求的地址
	 * @return 返回响应的信息
	 */
	public static String doGet(String url){
		//返回值信息
		String result = null;
		HttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet(url);
		try {
			//使用httpClient对象执行get请求
			HttpResponse response = client.execute(get);
			//将响应回来的信息转为字符串
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//关闭链接
			get.releaseConnection();
		}
		return result;
	}
	
	public static String doPost(String url, Map<String, String> map){
		String result = null;
		HttpPost httpPost = null;
		// 获取连接客户端工具
		HttpClient httpClient = HttpClients.createDefault();
        try {
        	// 创建POST请求对象
            httpPost = new HttpPost(url);
            String xml = WXPayUtil.mapToXml(map);
			StringEntity entityParams = new StringEntity(xml, "utf-8");
			httpPost.setEntity(entityParams);
	        // 浏览器表示
	        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
	        // 执行请求
	        HttpResponse response = httpClient.execute(httpPost);
	        // 获得响应的实体对象
	        HttpEntity entity = response.getEntity();
	        result = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
	        // 释放连接
	        if (null != httpPost) {
	        	httpPost.releaseConnection();
	        }
	    }

		return result;
	}

	public static String doPost(String url, String data){
		String result = null;
		HttpPost httpPost = null;
		// 获取连接客户端工具
		HttpClient httpClient = HttpClients.createDefault();
		try {
			// 创建POST请求对象
			httpPost = new HttpPost(url);
			httpPost.setEntity(new StringEntity(data, "utf-8"));
			// 浏览器表示
			httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			// 获得响应的实体对象
			result = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放连接
			if (null != httpPost) {
				httpPost.releaseConnection();
			}
		}

		return result;
	}
	
}
